package com.xbongbong.paas.help.factory.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.xbongbong.paas.abstracts.AbstractOperatorFieldHandler;
import com.xbongbong.paas.domain.entity.PaasFormDataEntity;
import com.xbongbong.paas.help.factory.OperatorFieldHandler;
import com.xbongbong.paas.field.FieldAttrEntity;
import com.xbongbong.paas.enums.FieldTypeEnum;
import com.xbongbong.paas.pojo.OperationsPojo;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.pro.businessrule.pojo.BusinessRuleInfoPojo;
import com.xbongbong.pro.constant.BusinessConstant;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.List;
import java.util.Objects;

/**
 * @author 吴峰
 * @version v1.0
 * @date 2020/3/4 21:11
 * @since v1.0
 */
@Component
public class OperatorAddressHandlerImpl extends AbstractOperatorFieldHandler {

    @Override
    public List<Integer> fieldType() {
        return Arrays.asList(FieldTypeEnum.ADDRESS.getType());
    }


    @Override
    public Object handlerTargetFormField(PaasFormDataEntity paasFormDataEntity, JSONObject data, FieldAttrEntity fieldAttrEntity, FieldAttrEntity targetField,
                                         BusinessRuleInfoPojo businessRuleInfoPojo, OperationsPojo operation) throws XbbException {
        Object object = operation.getValue();
        JSONObject address = data.getJSONObject(fieldAttrEntity.getAttr());
        setAddress(targetField, address);
        return address;
    }

    @Override
    public Object handlerFixedValue(FieldAttrEntity targetField, BusinessRuleInfoPojo businessRuleInfoPojo, OperationsPojo operation) throws XbbException {
        JSONObject address = JSON.parseObject(JSON.toJSONString(operation.getValue()));
        setAddress(targetField, address);
        return address;
    }

    private void setAddress(FieldAttrEntity targetField, JSONObject address) {
        Integer showDetailAddress = targetField.getShowDetailAddress();
        if (Objects.equals(0, showDetailAddress)) {
            // 当目标表单的地址无详细地址，而当前表单地址字段有详细地址，此时将当前表单中地址字段中的省、市、区赋值给目标表单中的地址字段，丢弃详细地址。
            address.put(BusinessConstant.ADDRESS, "");
        }
    }
}
